<template>
  <div class="page-container monitoring">
    <div class="page-header">
      <h2>概览</h2>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-icon running">
              <el-icon :size="40"><Loading /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.running_workflows }}</div>
              <div class="stat-label">运行中</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-icon success">
              <el-icon :size="40"><SuccessFilled /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.today_success }}</div>
              <div class="stat-label">今日成功</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-icon failed">
              <el-icon :size="40"><CircleCloseFilled /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.today_failed }}</div>
              <div class="stat-label">今日失败</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-icon rate">
              <el-icon :size="40"><TrendCharts /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ (statistics.success_rate * 100).toFixed(1) }}%</div>
              <div class="stat-label">成功率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 工作流实例列表 -->
    <el-card class="mt-20" shadow="never">
      <template #header>
        <div class="card-header">
          <span>工作流实例</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleCreateFromTemplate">
              <el-icon><Plus /></el-icon>
              从模板创建实例
            </el-button>
            <el-button type="text" @click="fetchAllInstances">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 合并后的单一表格 -->
      <el-table
        :data="allInstances"
        v-loading="loading"
        stripe
      >
        <el-table-column prop="id" label="实例ID" width="100" />
        <el-table-column prop="instance_name" label="实例名称" min-width="200" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="schedule_type" label="调度类型" width="160">
          <template #default="{ row }">
            <el-tag :type="getScheduleTypeTag(row.schedule_type)" size="small">
              {{ getScheduleTypeLabel(row.schedule_type) }}
            </el-tag>
            <div v-if="row.schedule_config" class="schedule-info">
              {{ getScheduleConfigInfo(row) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="耗时" width="120">
          <template #default="{ row }">
            {{ formatDuration(row.duration) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <!-- 未运行状态：显示运行按钮 -->
            <el-button
              v-if="row.status === '未运行'"
              type="primary"
              size="small"
              @click="handleStartInstance(row)"
            >
              <el-icon><VideoPlay /></el-icon>
              运行
            </el-button>
            <!-- 运行中状态：显示暂停按钮 -->
            <el-button
              v-if="row.status === '运行中'"
              size="small"
              @click="handlePause(row)"
            >
              暂停
            </el-button>
            <!-- 已暂停状态：显示恢复按钮 -->
            <el-button
              v-if="row.status === '已暂停'"
              size="small"
              @click="handleResume(row)"
            >
              恢复
            </el-button>
            <!-- 查看详情（所有状态都有） -->
            <el-button size="small" @click="handleViewDetail(row)">查看详情</el-button>
            <!-- 未运行状态：可以删除 -->
            <el-button
              v-if="row.status === '未运行'"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="fetchAllInstances"
        @current-change="fetchAllInstances"
      />
    </el-card>

    <!-- 从模板创建实例对话框 -->
    <el-dialog
      v-model="createInstanceDialogVisible"
      title="从模板创建实例"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form :model="instanceForm" label-width="120px">
        <el-form-item label="选择模板" required>
          <el-select
            v-model="instanceForm.template_id"
            placeholder="请选择工作流模板"
            style="width: 100%"
            filterable
            @change="handleTemplateSelect"
          >
            <el-option
              v-for="template in templates"
              :key="template.id"
              :label="`${template.name} (v${template.version})`"
              :value="template.id"
            >
              <div style="display: flex; justify-content: space-between;">
                <span>{{ template.name }}</span>
                <el-tag size="small" type="primary">v{{ template.version }}</el-tag>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="selectedTemplate" label="模板描述">
          <div class="template-description">
            {{ selectedTemplate.description || '无描述' }}
          </div>
        </el-form-item>

        <el-form-item label="实例名称" required>
          <el-input
            v-model="instanceForm.instance_name"
            placeholder="请输入实例名称"
          />
        </el-form-item>

        <el-form-item label="触发人">
          <el-input
            v-model="instanceForm.trigger_user"
            placeholder="请输入触发人"
          />
        </el-form-item>

        <!-- <el-form-item label="输入参数">
          <el-input
            v-model="instanceForm.input_params"
            type="textarea"
            :rows="4"
            placeholder='输入JSON格式的参数，例如: {"key": "value"}'
          />
        </el-form-item> -->
      </el-form>

      <template #footer>
        <el-button @click="createInstanceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleNextStep" :loading="createInstanceLoading">
          下一步
        </el-button>
      </template>
    </el-dialog>

    <!-- Cron表达式帮助对话框 -->
    <el-dialog
      v-model="cronHelpDialogVisible"
      title="Cron表达式帮助"
      width="600px"
    >
      <div class="cron-help">
        <h4>Cron表达式格式</h4>
        <p><code>分钟 小时 日 月 星期</code></p>

        <h4>常用示例</h4>
        <ul>
          <li><code>0 2 * * *</code> - 每天凌晨2点执行</li>
          <li><code>0 */4 * * *</code> - 每4小时执行一次</li>
          <li><code>30 8 * * 1-5</code> - 工作日上午8:30执行</li>
          <li><code>0 0 1 * *</code> - 每月1日零点执行</li>
          <li><code>*/15 * * * *</code> - 每15分钟执行一次</li>
        </ul>

        <h4>字段说明</h4>
        <el-table :data="cronFields" border>
          <el-table-column prop="field" label="字段" width="100" />
          <el-table-column prop="range" label="允许值" width="120" />
          <el-table-column prop="special" label="特殊字符" />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useWorkflowStore } from '@/stores/workflow'
import { useWorkflowTemplateStore } from '@/stores/workflowTemplate'
import { getMonitoringStatistics } from '@/api/monitoring'
import { startInstance, getNotStartedInstances } from '@/api/workflowTemplate'
import { deleteWorkflowInstance } from '@/api/workflow'
import dayjs from 'dayjs'

const router = useRouter()
const workflowStore = useWorkflowStore()
const templateStore = useWorkflowTemplateStore()

const statistics = ref({
  running_workflows: 0,
  today_success: 0,
  today_failed: 0,
  success_rate: 0
})

// 合并后的所有实例列表
const allInstances = ref([])
const loading = ref(false)
const total = ref(0)

const pagination = reactive({
  page: 1,
  pageSize: 20
})

let refreshTimer = null

// 创建实例相关状态
const createInstanceDialogVisible = ref(false)
const createInstanceLoading = ref(false)
const cronHelpDialogVisible = ref(false)
const templates = ref([])
const availableInstances = ref([])
const instanceForm = reactive({
  template_id: null,
  instance_name: '',
  trigger_user: '',
  input_params: '',
  cron_enabled: false,
  cron_expression: '',
  schedule_type: 'manual', // 默认立即执行
  scheduled_time: null,
  dependency_instance_ids: []
})

const selectedTemplate = computed(() => {
  return templates.value.find(t => t.id === instanceForm.template_id)
})

// 过滤可用实例 - 只显示未完成的实例
const filteredAvailableInstances = computed(() => {
  // 已完成的状态(不能被选择)
  const completedStatuses = ['已完成', '失败', '已取消']

  return availableInstances.value.filter(instance =>
    !completedStatuses.includes(instance.status)
  )
})

const cronFields = [
  { field: '分钟', range: '0-59', special: '* , - /' },
  { field: '小时', range: '0-23', special: '* , - /' },
  { field: '日', range: '1-31', special: '* , - ? / L W' },
  { field: '月', range: '1-12', special: '* , - /' },
  { field: '星期', range: '0-6', special: '* , - ? / L #' }
]

const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : ''
}

const formatDuration = (seconds) => {
  if (!seconds) return '-'
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  return `${hours}h ${minutes}m ${secs}s`
}

const getStatusType = (status) => {
  const typeMap = {
    '未运行': 'info',      // 新增：未运行状态（灰色）
    '初始化': 'primary',   // 蓝色
    '运行中': 'warning',   // 橙色
    '已完成': 'success',   // 绿色
    '失败': 'danger',      // 红色
    '暂停中': 'warning',   // 橙色
    '已暂停': 'info',      // 灰色
    '等待中': 'info',      // 灰色
    '已取消': 'info'       // 灰色
  }
  return typeMap[status] || 'info'
}

const getScheduleTypeTag = (scheduleType) => {
  const typeMap = {
    'manual': 'success',
    'scheduled': 'primary',
    'dependent': 'warning',
    'cron': 'success'
  }
  return typeMap[scheduleType] || 'info'
}

const getScheduleTypeLabel = (scheduleType) => {
  const labelMap = {
    'manual': '立即执行',
    'scheduled': '定时执行',
    'dependent': '依赖执行',
    'cron': 'CRON定时',
    'create_only': '仅创建'
  }
  return labelMap[scheduleType] || scheduleType
}

const getScheduleConfigInfo = (row) => {
  if (!row.schedule_config) return ''

  const config = row.schedule_config
  const scheduleType = row.schedule_type || 'manual'

  if (scheduleType === 'scheduled' && config.scheduled_time) {
    return `时间: ${dayjs(config.scheduled_time).format('MM-DD HH:mm')}`
  } else if (scheduleType === 'dependent' && config.dependency_instance_ids) {
    return `依赖: ${config.dependency_instance_ids.length}个实例`
  } else if (scheduleType === 'cron' && config.cron_expression) {
    return `表达式: ${config.cron_expression}`
  }

  return ''
}

const handleScheduleTypeChange = () => {
  // 切换调度类型时清空相关配置
  instanceForm.scheduled_time = null
  instanceForm.dependency_instance_ids = []
  instanceForm.cron_expression = ''
}

const disabledDate = (time) => {
  // 禁用过去的日期
  return time.getTime() < Date.now()
}

const fetchStatistics = async () => {
  try {
    const data = await getMonitoringStatistics()
    statistics.value = data
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取所有实例列表（包含未运行状态）
const fetchAllInstances = async () => {
  loading.value = true
  try {
    const data = await workflowStore.fetchWorkflowInstances({
      page: pagination.page,
      page_size: pagination.pageSize,
      include_not_started: true  // 包含未运行状态
    })
    allInstances.value = data.items || []
    total.value = data.total || 0
  } catch (error) {
    console.error('获取实例列表失败:', error)
    ElMessage.error('获取实例列表失败')
  } finally {
    loading.value = false
  }
}

// 启动未运行的实例
const handleStartInstance = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要启动实例 "${row.instance_name}" 吗？启动后将进入调度队列。`,
      '确认启动',
      {
        confirmButtonText: '启动',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    await startInstance(row.id)
    ElMessage.success('实例已启动，等待调度执行')

    // 刷新列表
    fetchAllInstances()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('启动实例失败:', error)
      ElMessage.error(error.response?.data?.detail || '启动实例失败')
    }
  }
}

// 删除实例
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除实例 "${row.instance_name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteWorkflowInstance(row.id)
    ElMessage.success('实例已删除')
    fetchAllInstances()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除实例失败:', error)
      ElMessage.error(error.response?.data?.detail || '删除实例失败')
    }
  }
}

const handleViewDetail = (row) => {
  router.push(`/workflows/instances/${row.id}`)
}

const handlePause = async (row) => {
  try {
    await workflowStore.pauseInstance(row.id)
    ElMessage.success('工作流已暂停')
    fetchAllInstances()
  } catch (error) {
    console.error('暂停工作流失败:', error)
  }
}

const handleResume = async (row) => {
  try {
    await workflowStore.resumeInstance(row.id)
    ElMessage.success('工作流已恢复')
    fetchAllInstances()
  } catch (error) {
    console.error('恢复工作流失败:', error)
  }
}

const handleCreateFromTemplate = async () => {
  // 加载模板列表和可用实例
  try {
    await templateStore.fetchTemplates({ page: 1, page_size: 100 })
    templates.value = templateStore.templates

    // 加载所有实例（用于依赖选择）
    const instancesData = await workflowStore.fetchWorkflowInstances({
      page: 1,
      page_size: 100,
      include_not_started: true
    })
    availableInstances.value = instancesData.items || []

    // 重置表单
    instanceForm.template_id = null
    instanceForm.instance_name = ''
    instanceForm.trigger_user = ''
    instanceForm.input_params = ''
    instanceForm.cron_enabled = false
    instanceForm.cron_expression = ''
    instanceForm.schedule_type = 'manual' // 重置为默认值：立即执行
    instanceForm.scheduled_time = null
    instanceForm.dependency_instance_ids = []

    createInstanceDialogVisible.value = true
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  }
}

const handleTemplateSelect = () => {
  // 当选择模板后，自动生成实例名称
  if (selectedTemplate.value) {
    instanceForm.instance_name = `${selectedTemplate.value.name}_${dayjs().format('YYYYMMDDHHmmss')}`
  }
}

const showCronHelp = () => {
  cronHelpDialogVisible.value = true
}

const handleNextStep = () => {
  if (!instanceForm.template_id) {
    ElMessage.warning('请选择模板')
    return
  }

  if (!instanceForm.instance_name) {
    ElMessage.warning('请输入实例名称')
    return
  }

  // 验证输入参数格式
  let inputParams = {}
  if (instanceForm.input_params) {
    try {
      inputParams = JSON.parse(instanceForm.input_params)
    } catch (e) {
      ElMessage.error('输入参数格式错误，请输入有效的JSON')
      return
    }
  }

  // 关闭对话框
  createInstanceDialogVisible.value = false

  // 跳转到编辑页面，通过 query 传递参数
  router.push({
    path: '/workflow-instances/create',
    query: {
      template_id: instanceForm.template_id,
      template_name: selectedTemplate.value?.name || '',
      instance_name: instanceForm.instance_name,
      trigger_user: instanceForm.trigger_user || '',
      input_params: JSON.stringify(inputParams)
    }
  })
}

// 自动刷新
const startAutoRefresh = () => {
  refreshTimer = setInterval(() => {
    fetchStatistics()
    fetchAllInstances()
  }, 30000) // 每30秒刷新一次
}

onMounted(() => {
  fetchStatistics()
  fetchAllInstances()
  startAutoRefresh()
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})
</script>

<style lang="scss" scoped>
.monitoring {
  .statistics-cards {
    .stat-card {
      display: flex;
      align-items: center;

      .stat-icon {
        margin-right: 20px;
        border-radius: 8px;
        padding: 15px;

        &.running {
          background-color: #ecf5ff;
          color: #409eff;
        }

        &.success {
          background-color: #f0f9ff;
          color: #67c23a;
        }

        &.failed {
          background-color: #fef0f0;
          color: #f56c6c;
        }

        &.rate {
          background-color: #fdf6ec;
          color: #e6a23c;
        }
      }

      .stat-content {
        .stat-value {
          font-size: 28px;
          font-weight: bold;
          margin-bottom: 5px;
        }

        .stat-label {
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-actions {
      display: flex;
      gap: 10px;
      align-items: center;
    }
  }

  .template-description {
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
    color: #606266;
    font-size: 14px;
  }

  .cron-help {
    h4 {
      margin-top: 20px;
      margin-bottom: 10px;
      font-size: 16px;
      color: #303133;

      &:first-child {
        margin-top: 0;
      }
    }

    code {
      background-color: #f5f7fa;
      padding: 2px 6px;
      border-radius: 3px;
      color: #e6a23c;
      font-family: 'Courier New', monospace;
    }

    ul {
      padding-left: 20px;

      li {
        margin-bottom: 8px;
        line-height: 1.8;
      }
    }
  }

  .form-tip {
    margin-top: 5px;
    font-size: 12px;
    color: #909399;
    line-height: 1.5;
  }

  .schedule-info {
    font-size: 12px;
    color: #606266;
    margin-top: 2px;
  }

  .template-description {
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
    color: #606266;
    font-size: 14px;
  }
}
</style>
